package com.test.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.test.R;
import com.test.entity.Icon;

import java.util.List;

/**
 * SpinnerAdapter选择器
 *
 * @Author Musique
 * 2020/8/5
 */
public class SpinnerAdapter extends BaseAdapter {

    private List<Icon> mIconList;
    private Context mContext;

    /**
     * 创建一个存储对象静态对象方法
     */
    public static class ViewHolder {
        ImageView img;
        TextView title;
    }

    public SpinnerAdapter(List<Icon> mIconList, Context mContext) {
        this.mContext = mContext;
        this.mIconList = mIconList;
    }

    @Override
    public int getCount() {
        return mIconList != null ? mIconList.size() : 0;
    }

    @Override
    public Object getItem(int i) {
        return mIconList.get(i).getTitle();
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        ViewHolder viewHolder = new ViewHolder();
        if (view == null) {
            // 获取定义资源格式
            view = LayoutInflater.from(mContext).inflate(R.layout.spinner_demo_style, viewGroup, false);
            // 查找对应id
            viewHolder.img = view.findViewById(R.id.img_icon);
            viewHolder.title = view.findViewById(R.id.tv_name);
            // 给view.tag付值，方便后续直接引用
            view.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) view.getTag();
        }

        // 给对象赋值
        viewHolder.title.setText(mIconList.get(i).getTitle());
        viewHolder.img.setBackgroundResource(mIconList.get(i).getAIcon());
        return view;
    }
}
